#include "CMapp.h"


CMapp::CMapp(void)
{
	Surf_Tileset = nullptr;
}

bool CMapp::OnLoad(char* File)
{
	TileList.clear();

	FILE* FileHandle = fopen(File, "r");
	if(FileHandle == nullptr)
		return false;

	for(int Y=0; Y < CSettings::MAP_HEIGHT; Y++)
	{
		for(int X=0; X < CSettings::MAP_WIDTH; X++)
		{
			CTile tempTile;
			fscanf(FileHandle, "%d:%d", &tempTile.TileID, &tempTile.TypeID);
			TileList.push_back(tempTile);
		}
		fscanf(FileHandle, "\n");
	}
	fclose(FileHandle);

	return true;
}

void CMapp::OnRender(SDL_Surface* Surf_Display, int MapX, int MapY)
{
	if(Surf_Display == nullptr)
		return;

	int TilesetWidth = Surf_Tileset->w / CSettings::TILE_SIZE;
	int TilesetHeight = Surf_Tileset->h / CSettings::TILE_SIZE;

	int ID = 0;

	for(int Y=0; Y < CSettings::MAP_HEIGHT; Y++)
	{
		for(int X=0; X < CSettings::MAP_WIDTH; X++)
		{
			if(TileList[ID].TypeID == TILE_TYPE_NONE)
			{
				ID++;
				continue;
			}

			int tX = MapX + (X * CSettings::TILE_SIZE);
			int tY = MapY + (Y * CSettings::TILE_SIZE);

			int TilesetX = (TileList[ID].TileID % TilesetWidth) * CSettings::TILE_SIZE;
			int TilesetY = (TileList[ID].TileID / TilesetWidth) * CSettings::TILE_SIZE;

			CSurface::OnDraw(Surf_Display, Surf_Tileset, tX, tY, TilesetX, TilesetY, CSettings::TILE_SIZE, CSettings::TILE_SIZE);

			ID++;
		}
	}
}

CTile* CMapp::GetTile(int X, int Y)
{
	int ID = 0;
	ID = X/CSettings::TILE_SIZE;
	ID += (CSettings::MAP_WIDTH * (Y / CSettings::TILE_SIZE));

	if(ID<0 || ID >= TileList.size())
		return nullptr;

	return &TileList[ID];
}

